<template>
  <div class="excel-form-container">
    <div class="excel-form-actions">
      <el-link type="primary" class="action-link"><el-icon><Document /></el-icon><span class="action-text">保存</span></el-link>
      <el-link type="primary" class="action-link"><el-icon><CopyDocument /></el-icon><span class="action-text">另存</span></el-link>
      <el-link type="primary" class="action-link"><el-icon><Refresh /></el-icon><span class="action-text">重置</span></el-link>
      <el-link type="primary" class="action-link"><el-icon><Connection /></el-icon><span class="action-text">测试连接</span></el-link>
      <el-link type="primary" class="action-link"><el-icon><Download /></el-icon><span class="action-text">导出</span></el-link>
      <el-link type="primary" class="action-link"><el-icon><Upload /></el-icon><span class="action-text">导入</span></el-link>
      <el-link type="danger" class="action-link"><el-icon><Delete /></el-icon><span class="action-text">删除</span></el-link>
      <el-link type="info" class="action-link"><el-icon><QuestionFilled /></el-icon><span class="action-text">帮助</span></el-link>
    </div>
    <el-tabs v-model="mainTab" class="main-form-tabs">
      <el-tab-pane label="配置" name="config">
        <el-tabs v-model="subTab" class="sub-form-tabs">
          <el-tab-pane label="连接属性配置" name="conn">
            <el-form ref="formRef" :model="form" :rules="formRules" :hide-required-asterisk="false" label-width="110px" class="excel-form">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="连接类型">
                    <el-input value="Excel" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="连接类型版本" required>
                    <el-select v-model="form.version" placeholder="请选择版本">
                      <el-option label="Excel 97-2003 (*.xls)" value="xls" />
                      <el-option label="Excel 2007 or later (*.xlsx)" value="xlsx" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- 第二行：连接名称、版本号 -->
                <el-col :span="12">
                  <el-form-item label="连接名称" required>
                    <el-input v-model="form.name" placeholder="请输入连接名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="版本号">
                    <el-input v-model="form.versionNo" disabled />
                  </el-form-item>
                </el-col>
                <!-- 第三行：资源组、连接描述 -->
                <el-col :span="12">
                  <el-form-item label="资源组" required>
                    <el-select v-model="form.group" placeholder="请选择资源组">
                      <el-option label="数据连接/公共资源组-数据连接" value="group1" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="连接描述">
                    <el-input v-model="form.desc" type="textarea" rows="2" placeholder="请输入连接描述" />
                  </el-form-item>
                </el-col>
                <!-- 文件属性分组框 -->
                <el-col :span="24">
                  <div class="group-box">
                    <div class="group-title">文件属性</div>
                    <div class="group-content">
                      <el-form-item label="数据来源" required>
                        <el-select v-model="form.route" placeholder="请选择">
                          <el-option label="本地文件" value="local" />
                          <el-option label="HTTP客户端" value="http" />
                          <el-option label="FTP / SFTP / FTPS Client" value="ftp" />
                        </el-select>
                      </el-form-item>
                      <template v-if="form.route === 'http'">
                        <div class="collapse-panel" v-for="(panel, idx) in httpPanels" :key="panel.key">
                          <div class="collapse-header" @click="togglePanel(idx)">
                            <span class="collapse-icon">{{ panel.open ? '-' : '+' }}</span>
                            <span class="collapse-title">{{ panel.title }}</span>
                          </div>
                          <div v-show="panel.open" class="collapse-content">
                            <template v-if="panel.key === 'panel1'">
                              <el-form-item label="HTTP方法" class="form-item-equal-width" prop="httpMethod" :rules="formRules.httpMethod">
                                <div class="form-item-input-wrapper">
                                  <el-select v-model="form.httpMethod" placeholder="请选择方法">
                                    <el-option label="GET" value="GET" />
                                    <el-option label="POST" value="POST" />
                                  </el-select>
                                </div>
                              </el-form-item>
                              <el-form-item label="URL" class="form-item-equal-width" prop="httpUrl" :rules="formRules.httpUrl">
                                <div class="form-item-input-wrapper">
                                  <el-input v-model="form.httpUrl" placeholder="http://" />
                                </div>
                              </el-form-item>
                              <el-form-item label="请求超时时间" class="form-item-equal-width" prop="httpTimeout" :rules="formRules.httpTimeout">
                                <div class="form-item-input-wrapper timeout-input-relative">
                                  <el-input
                                    v-model="form.httpTimeout"
                                    type="number"
                                    min="0"
                                    placeholder="请输入超时时间（毫秒）"
                                    class="timeout-input"
                                  />
                                  <el-tooltip content="如果在此时间（毫秒）内无法建立连接，则数据源将取消请求，查询失败" placement="top">
                                    <el-icon class="timeout-tooltip-icon"><QuestionFilled /></el-icon>
                                  </el-tooltip>
                                </div>
                              </el-form-item>
                              <el-form-item v-if="form.httpMethod === 'POST'" label="参数类型">
                                <el-radio-group v-model="paramType">
                                  <el-radio-button label="URL参数">URL参数</el-radio-button>
                                  <el-radio-button label="Body参数">Body参数</el-radio-button>
                                </el-radio-group>
                              </el-form-item>
                              <el-form-item v-if="form.httpMethod === 'POST' && paramType === 'Body参数'" label="Content type">
                                <el-select v-model="contentType" style="width: 100%;">
                                  <el-option v-for="item in contentTypeOptions" :key="item" :label="item" :value="item" />
                                </el-select>
                              </el-form-item>
                              <el-form-item v-if="form.httpMethod === 'POST' && paramType === 'Body参数'" label="请求体内容">
                                <el-input
                                  type="textarea"
                                  v-model="bodyContent"
                                  :rows="5"
                                  placeholder="请输入请求体内容"
                                  style="width: 100%;"
                                />
                              </el-form-item>
                              <el-form-item>
                                <div style="display: flex; align-items: center;">
                                  <el-link type="primary" @click="openHeadersDialog">HTTP请求头信息</el-link>
                                </div>
                              </el-form-item>
                              <!-- HTTP Headers 弹窗 -->
                              <el-dialog
                                title="HTTP请求头"
                                v-model="headersDialogVisible"
                                width="60%"
                                @close="onHeadersDialogCancel"
                              >
                                <div style="display: flex; justify-content: flex-end; margin-bottom: 8px;">
                                  <el-link type="primary" @click="addHeader">
                                    <el-icon style="vertical-align: middle; margin-right: 2px;"><Plus /></el-icon>
                                    新增
                                  </el-link>
                                  <el-link type="danger" style="margin-left: 16px;" :disabled="!selectedHeaders.length" @click="removeSelectedHeaders">
                                    <el-icon style="vertical-align: middle; margin-right: 2px;"><Delete /></el-icon>
                                    删除
                                  </el-link>
                                </div>
                                <el-table :data="headers" style="width: 100%" @selection-change="onHeaderSelectionChange" empty-text="">
                                  <el-table-column type="selection" width="40" />
                                  <el-table-column label="名称">
                                    <template #default="scope">
                                      <el-input v-model="scope.row.name" placeholder="请输入名称" />
                                    </template>
                                  </el-table-column>
                                  <el-table-column label="值">
                                    <template #default="scope">
                                      <el-input v-model="scope.row.value" placeholder="请输入值" />
                                    </template>
                                  </el-table-column>
                                  <el-table-column width="80">
                                    <template #default="scope">
                                      <el-button type="text" @click="removeHeader(scope.$index)">删除</el-button>
                                    </template>
                                  </el-table-column>
                                </el-table>
                                <template #footer>
                                  <el-button @click="onHeadersDialogCancel">取消</el-button>
                                  <el-button type="primary" @click="onHeadersDialogOk">确定</el-button>
                                </template>
                              </el-dialog>
                            </template>
                            <template v-if="panel.key === 'panel2'">
                              <el-form-item label="Authentication">
                                <el-select v-model="authenticationType" style="width: 100%;">
                                  <el-option label="无" value="无" />
                                  <el-option label="Basic" value="Basic" />
                                </el-select>
                              </el-form-item>
                              <div v-if="authenticationType === 'Basic'" style="display: flex; gap: 16px;">
                                <el-form-item label="用户名" style="flex: 1;" :rules="authenticationType === 'Basic' ? [{ required: true, message: '请输入用户名', trigger: 'blur' }] : []">
                                  <el-input v-model="authUsername" placeholder="请输入用户名" />
                                </el-form-item>
                                <el-form-item label="密码" style="flex: 1;" :rules="authenticationType === 'Basic' ? [{ required: true, message: '请输入密码', trigger: 'blur' }] : []">
                                  <el-input v-model="authPassword" placeholder="请输入密码" type="password" show-password />
                                </el-form-item>
                              </div>
                            </template>
                          </div>
                        </div>
                      </template>
                      <template v-if="['ftp', 'sftp', 'ftpsclient'].includes((form.route || '').toLowerCase())">
                        <el-form-item label="URL" prop="ftpUrl" :rules="formRules.ftpUrl">
                          <el-input v-model="ftpUrl" placeholder="ftp://" />
                        </el-form-item>
                        <el-form-item label="授权类型" prop="ftpAuthType" :rules="formRules.ftpAuthType">
                          <el-select v-model="ftpAuthType">
                            <el-option label="用户名密码校验" value="用户名密码校验" />
                            <el-option label="SSH密钥校验" value="SSH密钥校验" />
                          </el-select>
                        </el-form-item>
                        <el-form-item label="用户名" prop="ftpUsername" :rules="formRules.ftpUsername" v-if="ftpAuthType !== 'SSH密钥校验'">
                          <el-input v-model="ftpUsername" placeholder="请输入用户名" />
                        </el-form-item>
                        <el-form-item label="密码" prop="ftpPassword" :rules="formRules.ftpPassword" v-if="ftpAuthType !== 'SSH密钥校验'">
                          <el-input v-model="ftpPassword" placeholder="请输入密码" type="password" show-password />
                        </el-form-item>
                        <template v-if="ftpAuthType === 'SSH密钥校验'">
                          <el-form-item label="SSH密钥文件" prop="sshKeyFileName" :rules="formRules.sshKeyFileName">
                            <el-input
                              v-model="sshKeyFileName"
                              placeholder="请选择文件"
                              readonly
                              @click="triggerFileInput"
                              class="ssh-key-file-input"
                              style="cursor: pointer;"
                            >
                              <template #suffix>
                                <el-icon style="cursor:pointer;" @click.stop="triggerFileInput"><Upload /></el-icon>
                                <el-icon v-if="sshKeyFile" style="cursor:pointer;margin-left:8px;" @click.stop="clearSshKeyFile"><Delete /></el-icon>
                              </template>
                            </el-input>
                            <input
                              ref="fileInputRef"
                              type="file"
                              style="display:none"
                              @change="handleSshKeyFileChange"
                            />
                          </el-form-item>
                          <el-form-item label="SSH密钥密码" prop="sshKeyPassword" :rules="formRules.sshKeyPassword">
                            <el-input v-model="sshKeyPassword" placeholder="请输入SSH密钥密码" type="password" show-password />
                          </el-form-item>
                        </template>
                      </template>
                      <el-form-item v-if="form.route === 'local'" label="文件路径" class="file-path-item">
                        <el-input v-model="form.filePath" placeholder="请选择文件路径">
                          <template #suffix>
                            <el-icon style="cursor:pointer;" @click="fileDialogVisible = true"><FolderOpened /></el-icon>
                          </template>
                        </el-input>
                      </el-form-item>
                      <el-form-item label="工作表名称">
                        <el-input v-model="form.sheetName" placeholder="请输入需要解析的工作表名称，多个以英文,分割，默认解析第一个工作表" :disabled="form.extractAllSheets" />
                      </el-form-item>
                      <el-form-item label-width="0">
                        <el-row :gutter="20" style="width: 100%;">
                          <el-col :span="12">
                            <div style="display: flex; align-items: center; margin-left: 110px;">
                              <el-checkbox v-model="form.extractAllSheets">从所有工作表中提取数据</el-checkbox>
                              <el-tooltip content="如果选择此项，则Excel文件中所有的工作表都会被加载" placement="top">
                                <el-icon style="margin-left:6px; color:#909399; cursor:pointer;"><QuestionFilled /></el-icon>
                              </el-tooltip>
                            </div>
                          </el-col>
                          <el-col :span="12">
                            <div style="display: flex; align-items: center; margin-left: 110px;">
                              <el-checkbox v-model="form.hasHeader">存在工作表头</el-checkbox>
                              <el-tooltip content="如果选择此项，说明工作表第一行属于表头信息" placement="top">
                                <el-icon style="margin-left:6px; color:#909399; cursor:pointer;"><QuestionFilled /></el-icon>
                              </el-tooltip>
                            </div>
                          </el-col>
                        </el-row>
                      </el-form-item>
                    </div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="字符编码格式">
                    <el-radio-group v-model="form.charset">
                      <el-radio-button label="GDK">GDK</el-radio-button>
                      <el-radio-button label="UTF8">UTF8</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="管理属性配置" name="manage">
            <el-form label-width="110px" class="excel-form">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="标签">
                    <el-input placeholder="+" style="width: 60px; margin-right: 8px;" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="安全级别">
                    <el-radio-group v-model="manageForm.security">
                      <el-radio label="公开">公开</el-radio>
                      <el-radio label="秘密">秘密</el-radio>
                      <el-radio label="机密">机密</el-radio>
                      <el-radio label="绝密">绝密</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="项目名称" disabled>
                    <el-select v-model="manageForm.project" placeholder="请选择项目名称">
                      <el-option label="公共项目" value="公共项目" />
                      <el-option label="文件服务项目" value="文件服务项目" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="系统所属部门" >
                    <el-input v-model="manageForm.department" disabled class="readonly-disabled-input" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="系统负责人">
                    <el-input v-model="manageForm.owner" disabled class="readonly-disabled-input" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="开发商名称">
                    <el-input v-model="manageForm.developer" disabled class="readonly-disabled-input" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
      <el-tab-pane label="视图" name="view">
        <el-card class="view-card" shadow="never">
          <div class="view-container">
            <div class="search-bar">
              <el-input 
                v-model="searchKeyword" 
                placeholder="搜索字段" 
                style="width: 100%;"
                clearable
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
                <template #suffix>
                  <el-icon style="cursor: pointer;"><FullScreen /></el-icon>
                </template>
              </el-input>
            </div>
            <div class="tree-container">
              <el-tree
                :data="treeData"
                :props="treeProps"
                :filter-node-method="filterNode"
                ref="treeRef"
                node-key="id"
                default-expand-all
                class="view-tree"
              >
                <template #default="{ node, data }">
                  <span class="tree-node">
                    <el-icon v-if="data.type === 'database'" class="tree-icon database-icon">
                      <Connection />
                    </el-icon>
                    <el-icon v-else-if="data.type === 'folder'" class="tree-icon folder-icon">
                      <FolderOpened />
                    </el-icon>
                    <el-icon v-else-if="data.type === 'table'" class="tree-icon table-icon">
                      <Document />
                    </el-icon>
                    <el-icon v-else class="tree-icon field-icon">
                      <Document />
                    </el-icon>
                    <span class="tree-label">{{ node.label }}</span>
                  </span>
                </template>
              </el-tree>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="版本" name="version">
        <el-table :data="versionTableData" style="width: 100%" class="version-table">
          <el-table-column prop="connectionName" label="连接名称" min-width="120" />
          <el-table-column prop="versionNumber" label="版本号" min-width="100">
            <template #default="scope">
              <el-link type="primary" :underline="false">{{ scope.row.versionNumber }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="operationalStatus" label="工作状态" min-width="100">
            <template #default="scope">
              <el-tag type="success" effect="light" size="small">{{ scope.row.operationalStatus }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="testStatus" label="测试状态" min-width="100">
            <template #default="scope">
              <el-tag type="info" effect="light" size="small">{{ scope.row.testStatus }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="project" label="所属项目" min-width="120" />
          <el-table-column prop="updateTime" label="更新时间" min-width="150" />
          <el-table-column prop="updater" label="更新人" min-width="100" />
          <el-table-column prop="createTime" label="创建时间" min-width="150" />
          <el-table-column prop="creator" label="创建人" min-width="100" />
          <el-table-column label="操作" min-width="120" fixed="right">
            <template #default="scope">
              <el-link type="primary" :underline="false" style="margin-right: 8px;">变更</el-link>
              <el-link type="primary" :underline="false">另存</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="使用说明" name="help">
        <div class="help-doc">
          <h2>数据连接</h2>
          <div class="help-section">
            <div class="help-title">一、概述</div>
            <div class="help-desc">
              数据连接是指一种能够规范或透明访问和管理数据的服务。帮助开发者快速集成数据或集成到企业业务系统。通过统一的连接管理界面，<b>您可以配置、测试所有数据源，并在各种应用场景中复用这些连接。</b>
            </div>
          </div>
          <div class="help-section">
            <div class="help-title">二、功能介绍</div>
            <div class="help-subtitle">（一）数据连接的类型</div>
            <div class="help-desc">
              我们的数据库连接支持以下 <b>39</b> 个类型的数据源：<br />
              <span class="help-underline">关系型数据库（21个）</span>：
            </div>
            <div class="help-db-select-demo">
              <div class="db-select-box">
                <div class="db-select-left">
                  <el-input placeholder="请输入关键字" size="small" class="db-search" style="width: 220px; margin-bottom: 10px;" />
                  <el-menu default-active="SQL DB" class="db-menu" :router="false">
                    <el-menu-item index="全部">全部 (39)</el-menu-item>
                    <el-menu-item index="最近使用">最近使用 (5)</el-menu-item>
                    <el-menu-item index="标准协议">标准协议 (13)</el-menu-item>
                    <el-menu-item index="SQL DB">SQL DB (21)</el-menu-item>
                    <el-menu-item index="NOSQL DB">NOSQL DB (1)</el-menu-item>
                    <el-menu-item index="文档格式">文档格式 (6)</el-menu-item>
                    <el-menu-item index="企业管理系统">企业管理系统 (1)</el-menu-item>
                  </el-menu>
                </div>
                <div class="db-select-right">
                  <el-row :gutter="12">
                    <el-col :span="6" v-for="db in dbDemoList" :key="db.name">
                      <el-card class="db-demo-card">
                        <div class="db-demo-logo">{{ db.name }}</div>
                        <div class="db-demo-label">{{ db.label }}</div>
                      </el-card>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog v-model="fileDialogVisible" title="请选择文件" width="80%" top="30px" :close-on-click-modal="false">
      <div class="file-dialog-content">
        <div class="file-dialog-path-bar">
          <div class="file-dialog-path-left">
            <el-button size="small" :icon="ArrowLeftBold" @click="handleFileBack" :disabled="!canBack" circle></el-button>
            <el-button size="small" :icon="ArrowRightBold" @click="handleFileForward" :disabled="!canForward" circle></el-button>
            <el-button size="small" :icon="ArrowUpBold" @click="handleFileUp" :disabled="fileDialogPath.length <= 1" circle></el-button>
            <el-button size="small" :icon="FolderAdd" @click="handleNewFolder" circle></el-button>
          </div>
          <div class="file-dialog-path-breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-for="(seg, idx) in fileDialogPath" :key="idx" @click="handlePathClick(idx)" style="cursor:pointer;">{{ seg }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="file-dialog-path-right">
            <el-button size="small" :icon="Refresh" @click="handleFileRefresh" circle></el-button>
            <el-button size="small" :icon="House" @click="handleFileHome" circle></el-button>
          </div>
        </div>
        <div class="file-dialog-table-scroll">
          <el-table :data="fileDialogList" highlight-current-row @current-change="handleFileSelect" style="margin-top: 8px;">
            <el-table-column prop="name" label=" " min-width="300">
              <template #default="scope">
                <el-icon v-if="scope.row.type === 'dir'" style="margin-right:4px;"><FolderOpened /></el-icon>
                <el-icon v-else style="margin-right:4px;"><Document /></el-icon>
                <span @dblclick="scope.row.type === 'dir' && handleDirDblClick(scope.row)">{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="size" label=" " min-width="80" align="right">
              <template #default="scope">
                <span v-if="scope.row.size">{{ scope.row.size }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="file-dialog-footer">
          <span>文件名称</span>
          <el-input v-model="fileDialogSelectedName" style="width: 100%;" readonly />
        </div>
      </div>
      <template #footer>
        <el-button @click="fileDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFileDialogOk">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Document, CopyDocument, Refresh, Connection, Download, Upload, Delete, QuestionFilled, FolderOpened, ArrowLeftBold, ArrowRightBold, ArrowUpBold, FolderAdd, House, Plus, Search, FullScreen } from '@element-plus/icons-vue'
const mainTab = ref('config')
const subTab = ref('conn')
const form = ref({
  name: '',
  group: '',
  desc: '',
  filePath: '',
  username: '',
  password: '',
  schema: '',
  charset: 'UTF8',
  version: 'xlsx', // Added version field
  route: '请选择', // Added route field
  versionNo: 'V1.0', // Added versionNo field
  sheetName: '', // Added sheetName field
  extractAllSheets: false, // Added extractAllSheets field
  extractSheetName: false, // Added extractSheetName field
  startCell: '', // Added startCell field
  endCell: '', // Added endCell field
  hasHeader: false, // Added hasHeader field
  httpMethod: 'GET', // Added httpMethod field
  httpUrl: '', // Added httpUrl field
  httpTimeout: 120000, // Added httpTimeout field
})
const manageForm = ref({
  security: '公开',
  project: '公共项目',
  department: '根机构', // 系统所属部门
  owner: '',           // 系统负责人
  developer: ''        // 开发商名称
})
const advancedForm = ref({
  checkoutValidate: false,
  checkinValidate: false,
  initConn: 1,
  maxActiveConn: 10,
  minActiveConn: 1,
  maxWait: 0,
  minIdleConn: 0,
  maxIdleConn: 0,
  removeLeak: false,
  leakTimeout: 0,
  printStack: false,
  connParam: '',
  firstSql: '',
})
const versionTableData = ref([
  {
    connectionName: 'EXCEL-学生信息表',
    versionNumber: 'V1.0',
    operationalStatus: '启用',
    testStatus: '未测试',
    project: '公共项目',
    updateTime: '2025/07/25 13:30:48',
    updater: 'chenyl',
    createTime: '2025/07/23 14:58:04',
    creator: 'chenyl'
  }
])
const dbDemoList = [
  { name: 'MySQL', label: 'Mysql' },
  { name: 'Oracle', label: 'Oracle' },
  { name: 'SqlServer', label: 'SqlServer' },
  { name: 'Postgresql', label: 'Postgresql' },
  { name: 'DM', label: 'DM' },
  { name: 'Kingbase', label: 'Kingbase' },
  { name: 'GBase8s', label: 'GBase8s' },
  { name: 'OceanBaseByMySQL', label: 'OceanBaseByMySQL' },
  { name: 'OceanBaseByOracle', label: 'OceanBaseByOracle' },
  { name: 'VastbaseG100ByMySQL', label: 'VastbaseG100ByMySQL' },
  { name: 'SAP HANA', label: 'SAP HANA' },
]
const httpPanels = ref([
  { key: 'panel1', title: 'HTTP请求配置', content: '这里是面板一的内容', open: false },
  { key: 'panel2', title: '授权信息', content: '这里是面板二的内容', open: false },
])
function togglePanel(idx) {
  httpPanels.value[idx].open = !httpPanels.value[idx].open
}
const fileDialogVisible = ref(false)
const fileDialogPath = ref(['D:', 'Software', 'MySQL-8.4.3-winx64-LTS'])
const fileDialogList = ref([
  { name: 'bin', type: 'dir' },
  { name: 'data', type: 'dir' },
  { name: 'docs', type: 'dir' },
  { name: 'include', type: 'dir' },
  { name: 'lib', type: 'dir' },
  { name: 'logs', type: 'dir' },
  { name: 'share', type: 'dir' },
  { name: 'config.txt', type: 'file', size: '1KB' },
  { name: 'LICENSE', type: 'file', size: '252KB' },
  { name: 'my.ini', type: 'file', size: '2KB' },
  { name: 'README', type: 'file', size: '1KB' },
])
const fileDialogSelected = ref(null)
const fileDialogSelectedName = ref('')
const fileDialogHistory = ref([['D:', 'Software', 'MySQL-8.4.3-winx64-LTS']])
const fileDialogHistoryIndex = ref(0)
const canBack = computed(() => fileDialogHistoryIndex.value > 0)
const canForward = computed(() => fileDialogHistoryIndex.value < fileDialogHistory.value.length - 1)

function updateFileDialogPath(newPath) {
  fileDialogPath.value = [...newPath]
  // TODO: 这里调用后端API获取目录内容，更新fileDialogList.value
}
function handleFileBack() {
  if (canBack.value) {
    fileDialogHistoryIndex.value--
    updateFileDialogPath(fileDialogHistory.value[fileDialogHistoryIndex.value])
  }
}
function handleFileForward() {
  if (canForward.value) {
    fileDialogHistoryIndex.value++
    updateFileDialogPath(fileDialogHistory.value[fileDialogHistoryIndex.value])
  }
}
function handleFileUp() {
  if (fileDialogPath.value.length > 1) {
    const newPath = fileDialogPath.value.slice(0, -1)
    fileDialogHistory.value = fileDialogHistory.value.slice(0, fileDialogHistoryIndex.value + 1)
    fileDialogHistory.value.push(newPath)
    fileDialogHistoryIndex.value++
    updateFileDialogPath(newPath)
  }
}
function handleNewFolder() {
  // TODO: 调用后端API新建文件夹
  // 可弹出输入框让用户输入新文件夹名
}
function handleFileRefresh() {
  // TODO: 调用后端API刷新当前目录
}
function handleFileHome() {
  const rootPath = ['D:']
  fileDialogHistory.value = [rootPath]
  fileDialogHistoryIndex.value = 0
  updateFileDialogPath(rootPath)
}
function handleFileSelect(row) {
  fileDialogSelected.value = row
  fileDialogSelectedName.value = row ? row.name : ''
}
function handleFileDialogOk() {
  if (fileDialogSelected.value && fileDialogSelected.value.type === 'file') {
    // 拼接全路径
    const fullPath = fileDialogPath.value.join('/') + '/' + fileDialogSelected.value.name
    form.value.filePath = fullPath
    fileDialogVisible.value = false
  }else{
    alert('请选择文件')
  }
}
function handlePathClick(idx) {
  if (idx < fileDialogPath.value.length - 1) {
    const newPath = fileDialogPath.value.slice(0, idx + 1)
    fileDialogHistory.value = fileDialogHistory.value.slice(0, fileDialogHistoryIndex.value + 1)
    fileDialogHistory.value.push(newPath)
    fileDialogHistoryIndex.value++
    updateFileDialogPath(newPath)
  }
}
function handleDirDblClick(row) {
  const newPath = [...fileDialogPath.value, row.name]
  fileDialogHistory.value = fileDialogHistory.value.slice(0, fileDialogHistoryIndex.value + 1)
  fileDialogHistory.value.push(newPath)
  fileDialogHistoryIndex.value++
  updateFileDialogPath(newPath)
}

const headersDialogVisible = ref(false)
const headers = ref([])
let headersBackup = []

const addHeader = () => {
  headers.value.push({ name: '', value: '' })
}
const removeHeader = (index) => {
  headers.value.splice(index, 1)
}
const onHeadersDialogCancel = () => {
  headersDialogVisible.value = false
  // 恢复上次保存的内容
  headers.value = headersBackup.map(h => ({ ...h }))
}
const onHeadersDialogOk = () => {
  headersDialogVisible.value = false
  // 保存当前内容
  headersBackup = headers.value.map(h => ({ ...h }))
}
const openHeadersDialog = () => {
  headersBackup = headers.value.map(h => ({ ...h }))
  headersDialogVisible.value = true
}

// 视图选项卡相关数据
const searchKeyword = ref('')
const treeRef = ref()

// 树形结构数据
const treeData = ref([
  {
    id: '1',
    label: '学生工作表',
    type: 'database',
    children: [
      {
        id: '1-1',
        label: 'Sheet1',
        type: 'table',
        children: [
          { id: '1-1-1', label: '姓名', type: 'field' },
          { id: '1-1-2', label: '年龄', type: 'field' },
          { id: '1-1-3', label: '出生日期', type: 'field' },
          { id: '1-1-4', label: '身高', type: 'field' },
          { id: '1-1-5', label: '成绩', type: 'field' }
        ]
      },
      {
        id: '1-2',
        label: 'Sheet2',
        type: 'table',
        children: [
          { id: '1-2-1', label: '姓名', type: 'field' },
          { id: '1-2-2', label: '年龄', type: 'field' },
          { id: '1-2-3', label: '出生日期', type: 'field' },
          { id: '1-2-4', label: '身高', type: 'field' },
          { id: '1-2-5', label: '成绩', type: 'field' },
          { id: '1-2-6', label: '爱好', type: 'field' }
        ]
      },
      {
        id: '1-3',
        label: 'Sheet3',
        type: 'table',
        children: [
          { id: '1-3-1', label: '姓名', type: 'field' },
          { id: '1-3-2', label: '年龄', type: 'field' },
          { id: '1-3-3', label: '出生日期', type: 'field' },
          { id: '1-3-4', label: '身高', type: 'field' },
          { id: '1-3-5', label: '成绩', type: 'field' },
          { id: '1-3-6', label: '特长', type: 'field' }
        ]
      }
    ]
  }
])

const treeProps = {
  children: 'children',
  label: 'label'
}

const filterNode = (value, data) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}

const handleSearch = () => {
  if (treeRef.value) {
    treeRef.value.filter(searchKeyword.value)
  }
}

// 监听搜索关键词变化
watch(searchKeyword, (newValue) => {
  if (treeRef.value) {
    treeRef.value.filter(newValue)
  }
})
const selectedHeaders = ref([])
const onHeaderSelectionChange = (selection) => {
  selectedHeaders.value = selection
}
const removeSelectedHeaders = () => {
  if (!selectedHeaders.value.length) return
  headers.value = headers.value.filter(row => !selectedHeaders.value.includes(row))
  selectedHeaders.value = []
}
const paramType = ref('URL参数')
const contentType = ref('application/json')
const bodyContent = ref('')
const contentTypeOptions = [
  'application/json',
  'application/xml',
  'text/csv',
  'text/html',
  'text/json',
  'text/plain',
  'text/xml'
]
const authenticationType = ref('无')
const authUsername = ref('')
const authPassword = ref('')

const ftpAuthType = ref('用户名密码校验')
const ftpUrl = ref('')
const ftpUsername = ref('')
const ftpPassword = ref('')
const sshKeyFile = ref(null)
const sshKeyPassword = ref('')
const fileInputRef = ref()
const sshKeyFileName = computed(() => sshKeyFile.value ? sshKeyFile.value.name : '')
function handleSshKeyFileChange(e) {
  const file = e.target.files && e.target.files[0]
  if (file) sshKeyFile.value = file
}
function triggerFileInput() {
  fileInputRef.value && fileInputRef.value.click()
}
function clearSshKeyFile() {
  sshKeyFile.value = null
  if (fileInputRef.value) fileInputRef.value.value = ''
}

const formRules = {
  httpMethod: [
    {
      required: computed(() => form.route === 'HTTP客户端'),
      message: '请选择HTTP方法',
      trigger: 'change'
    }
  ],
  httpUrl: [
    {
      required: computed(() => form.route === 'HTTP客户端'),
      message: '请输入URL',
      trigger: 'blur'
    }
  ],
  httpTimeout: [
    {
      required: computed(() => form.route === 'HTTP客户端'),
      message: '请输入请求超时时间',
      trigger: 'blur'
    }
  ],
  ftpUrl: [
    {
      required: computed(() => ['ftp', 'sftp', 'ftpsclient'].includes((form.route || '').toLowerCase())),
      message: '请输入URL',
      trigger: 'blur'
    }
  ],
  ftpAuthType: [
    {
      required: computed(() => ['ftp', 'sftp', 'ftpsclient'].includes((form.route || '').toLowerCase())),
      message: '请选择授权类型',
      trigger: 'change'
    }
  ],
  ftpUsername: [
    {
      required: computed(() => ['ftp', 'sftp', 'ftpsclient'].includes((form.route || '').toLowerCase())),
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  ftpPassword: [
    {
      required: computed(() => ['ftp', 'sftp', 'ftpsclient'].includes((form.route || '').toLowerCase())),
      message: '请输入密码',
      trigger: 'blur'
    }
  ],
  sshKeyFileName: [
    {
      required: computed(() => ['sftp', 'ftpsclient'].includes((form.route || '').toLowerCase())),
      message: '请选择SSH密钥文件',
      trigger: 'change'
    }
  ],
  sshKeyPassword: [
    {
      required: computed(() => ['sftp', 'ftpsclient'].includes((form.route || '').toLowerCase())),
      message: '请输入SSH密钥密码',
      trigger: 'blur'
    }
  ]
}

const formRef = ref()

function onSubmit() {
  formRef.value.validate((valid) => {
    if (valid) {
      // 校验通过，执行提交逻辑
    } else {
      // 校验不通过，可提示或阻止提交
    }
  })
}
</script>

<style scoped>
.excel-form-container {
  background: #fff;
  border-radius: 8px;
  padding: 24px 32px 16px 32px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.06);
  min-height: 400px;
}
.main-form-tabs {
  margin-bottom: 0;
  font-size: 13px;
}
.sub-form-tabs {
  margin-top: 16px;
  font-size: 13px;
}
:deep(.el-tabs__item) {
  font-size: 13px !important;
}
.excel-form {
  margin-top: 24px;
}
.adv-form .adv-section {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 18px;
  background: #fafbfc;
  padding: 12px 18px 8px 18px;
}
.adv-form .adv-section-title {
  font-size: 15px;
  font-weight: 500;
  color: #409eff;
  margin-bottom: 8px;
  text-align: left;
}
.adv-form .el-form-item__label {
  width: 126px !important; /* 原120px增加5% */
  min-width: 126px !important;
}
.adv-form .el-form-item__content {
  flex: 1 1 0%;
  max-width: calc(100% - 126px);
}
.adv-form .el-input,
.adv-form .el-input-number,
.adv-form .el-switch,
.adv-form .el-radio-group {
  width: 150% !important;
  min-width: 0;
}
.excel-form-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}
.action-link {
  font-size: 13px;
  padding: 0 4px;
  display: flex;
  align-items: center;
}
.action-text {
  margin-left: 3px;
}
.help-doc {
  padding: 24px 32px 16px 32px;
  background: #fff;
  border-radius: 8px;
  min-height: 400px;
}
.help-title {
  font-size: 18px;
  font-weight: bold;
  margin: 18px 0 8px 0;
}
.help-subtitle {
  font-size: 15px;
  font-weight: 500;
  margin: 12px 0 6px 0;
}
.help-desc {
  font-size: 14px;
  margin-bottom: 10px;
}
.help-underline {
  text-decoration: underline;
  font-weight: 500;
}
.db-select-box {
  display: flex;
  background: #fafbfc;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-top: 12px;
  padding: 16px 12px 12px 12px;
}
.db-select-left {
  width: 180px;
  margin-right: 18px;
}
.db-menu {
  background: transparent;
  border: none;
}
.db-select-right {
  flex: 1;
}
.db-demo-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 70px;
  margin-bottom: 10px;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
  font-size: 13px;
  background: #fff;
}
.db-demo-logo {
  font-weight: bold;
  color: #409eff;
  margin-bottom: 2px;
}
.db-demo-label {
  color: #666;
  font-size: 12px;
}
.group-box {
  border: 1.5px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 18px;
  background: #fafbfc;
  position: relative;
  padding: 18px 18px 8px 18px;
}
.group-title {
  position: absolute;
  top: -13px;
  left: 18px;
  background: #fafbfc;
  color: #666;
  font-size: 14px;
  padding: 0 10px;
  z-index: 1;
}
.group-content {
  margin-top: 0;
}
.file-path-item .el-form-item__content {
  flex: 1 1 0%;
  max-width: calc(100% - 126px); /* Adjusted for suffix */
}
.file-path-item .el-input {
  width: 100% !important; /* Ensure input takes full width */
  min-width: 0;
}
.file-path-item .el-input__inner {
  padding-right: 30px; /* Adjust padding for suffix */
}
.file-path-item .el-input__suffix {
  right: 0; /* Position suffix to the right */
}
.file-dialog-content {
  background: #fff;
  min-height: 400px;
  padding-left: 32px;
  padding-right: 32px;
}
.file-dialog-path-bar {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.file-dialog-path-left {
  display: flex;
  align-items: center;
  gap: 4px;
}
.file-dialog-path-breadcrumb {
  flex: 1;
  margin: 0 12px;
  min-width: 0;
  overflow-x: auto;
}
.file-dialog-path-right {
  display: flex;
  align-items: center;
  gap: 4px;
}
.file-dialog-table-scroll {
  max-height: 340px;
  overflow-y: auto;
  background: #fff;
  border-radius: 4px;
}
.file-dialog-table-scroll::-webkit-scrollbar {
  width: 8px;
  background: #f0f0f0;
  border-radius: 4px;
}
.file-dialog-table-scroll::-webkit-scrollbar-thumb {
  background: #d4d7de;
  border-radius: 4px;
}
.file-dialog-footer {
  display: flex;
  align-items: center;
  margin-top: 12px;
}
.file-dialog-footer .el-input {
  width: 100% !important;
  margin-left: 8px;
}
.file-dialog-footer span {
  min-width: 84px;
  display: inline-block;
}
.file-dialog-path-bar .el-button .el-icon {
  color: #606266 !important;
  font-size: 18px;
}
.sheet-checkbox-row {
  display: flex !important;
  flex-direction: row !important;
  align-items: center;
  padding-left: 0;
  padding-right: 0;
}
.checkbox-row-left {
  flex: 1;
  display: flex;
  align-items: center;
  min-width: 0;
}
.checkbox-row-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  min-width: 0;
}
.collapse-panel {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 10px;
  background: #fafbfc;
  padding: 0 12px 0 12px;
}
.collapse-header {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 0;
  font-size: 14px;
  color: #606266;
  font-weight: normal;
}
.collapse-icon {
  display: inline-block;
  width: 18px;
  text-align: center;
  font-size: 18px;
  color: #409eff;
  margin-right: 6px;
  font-weight: bold;
}
.collapse-content {
  padding: 8px 0 12px 24px;
  color: #666;
  font-size: 14px;
}
.timeout-form-item .el-form-item__content {
  flex: 1 1 0%;
}
.timeout-input-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
}
.timeout-input-wrapper .el-input {
  flex: 1;
}
.timeout-input-wrapper .el-tooltip {
  margin-left: 8px;
}
.form-item-equal-width .el-form-item__label {
  width: 100px;
  min-width: 100px;
  text-align: right;
}
.form-item-equal-width .el-form-item__content {
  width: calc(100% - 100px);
  max-width: none;
  flex: none;
}
.form-item-input-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
}
.form-item-input-wrapper .el-input,
.form-item-input-wrapper .el-select {
  width: 100%;
  flex: 1 1 0%;
}
.form-item-input-wrapper .el-tooltip {
  margin-left: 8px;
}
.timeout-input-relative {
  position: relative;
  width: 100%;
  display: flex;
  align-items: center;
}
.timeout-input {
  width: 100%;
}
.timeout-tooltip-icon {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  cursor: pointer;
  z-index: 2;
  font-size: 18px;
  pointer-events: auto;
  background: transparent;
}
.square-radio-group .el-radio__input,
.square-radio-group .el-radio__inner {
  border-radius: 2px !important;
}
.ssh-key-file-input:hover {
  cursor: pointer;
}
.ssh-key-file-input:hover input,
.ssh-key-file-input input:hover {
  cursor: pointer !important;
}
.ssh-key-file-input .el-input__wrapper {
  cursor: pointer !important;
}
.ssh-key-file-input input[readonly] {
  cursor: pointer !important;
}
.el-input.ssh-key-file-input,
.el-input.ssh-key-file-input .el-input__wrapper,
.el-input.ssh-key-file-input input[readonly] {
  cursor: pointer !important;
}
:deep(.el-table__header th) {
  font-size: 13px;
}
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #c0c4cc;
}
.empty-icon {
  margin-bottom: 16px;
}
.empty-text {
  font-size: 14px;
  color: #c0c4cc;
}
.readonly-disabled-input .el-input__wrapper,
.readonly-disabled-input input[readonly] {
  cursor: not-allowed !important;
}

/* 视图选项卡样式 */
.view-card {
  height: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.view-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-bar {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.tree-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.view-tree {
  background: transparent;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
}

.tree-icon {
  margin-right: 8px;
  font-size: 16px;
}

.database-icon {
  color: #409eff;
}

.folder-icon {
  color: #e6a23c;
}

.table-icon {
  color: #67c23a;
}

.field-icon {
  color: #909399;
}

.tree-label {
  font-size: 14px;
  color: #303133;
}

/* 版本表格样式 */
.version-table {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.version-table .el-table__header {
  background-color: #f5f7fa;
}

.version-table .el-table__header th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  font-size: 14px;
}

.version-table .el-table__body td {
  padding: 12px 0;
}

.version-table .el-link {
  font-size: 14px;
}

.version-table .el-tag {
  border-radius: 2px;
}
</style>  